package main

import (
	"fmt"
	//"unsafe"
	"net"
	"log"
	"encoding/binary"

	"github.com/fananchong/cstruct-go"
)

/*
typedef struct _EventMessage
{
    uint8_t  id;
    uint8_t  type;
    uint16_t para;
    uint32_t len;
    unsigned char payload[0];
} EventMessage;

*/

type EventMessage struct {
	id 	uint8
	class	uint8 
	para	uint16
	length  uint32
}


func handleConnection(conn net.Conn) {
    defer conn.Close()
    buf := make([]byte, 8)
    for {
	data := EventMessage{}
        n, err := conn.Read(buf)
        if err != nil {
            log.Println(err)
            return
        }

	//fmt.Println("n = ", n);
	err = cstruct.Unmarshal(buf, &data)
        if err != nil {
                fmt.Println(err.Error())
        }
	//fmt.Println("len(b) =", unsafe.Sizeof(data))
	//fmt.Println(data)
	
	var testByte []byte = make([]byte, 4)
	binary.BigEndian.PutUint32(testByte, data.length)
	
	convInt := binary.LittleEndian.Uint32(testByte)
	//fmt.Println("convInt = ", convInt)
	data.length = convInt;	
	
	body := make([]byte, data.length + 2)
        n, err = conn.Read(body)
        if err != nil {
            log.Println(err)
            return
        }
	//fmt.Println("n = ", n);
	
	fmt.Printf("%s\n", string(body[:n - 2]))

	//fmt.Println("len(b) =", unsafe.Sizeof(data))
	//fmt.Println("struct data len = ", len())

	/*
        fmt.Printf("Received: %s", string(buf[:n]))
        data := strings.ToUpper(string(buf[:n]))
        _, err = conn.Write([]byte(data))
        if err != nil {
            log.Println(err)
            return
        }
	*/
    }
}


func main() {

	addr, err := net.ResolveTCPAddr("tcp", ":8800")
	if err != nil {
		log.Fatal(err)
	}
	ln, err := net.ListenTCP("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()
	fmt.Println("Listening on port 8800")
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go handleConnection(conn)
	}


/*	
	b := StructB{}
	b.B1 = 127
	b.B2.A1 = 56
	b.B2.A2 = 999
	b.B2.A3[0] = 0
	b.B2.A3[1] = 1
	b.B2.A3[2] = 2
	b.B2.A3[3] = 3
	b.B2.A3[4] = 4
	b.B3 = 8888
	b.B4 = 88.8
	b.B5[0] = b.B2
	b.B5[1] = b.B2
	b.B5[2] = b.B2

	data, _ := cstruct.Marshal(&b)

	fmt.Println("len(b) =", unsafe.Sizeof(b))
	fmt.Println("struct data len = ", len(data))
	fmt.Println("struct data is:")
	for i := 0; i < len(data); i++ {
		fmt.Printf("%d ", data[i])
	}
	
	c := StructB{}
	err := cstruct.Unmarshal(data, &c)
	if err != nil {
		fmt.Println(err.Error())
	}

	fmt.Println("\nmydata: ", c)
*/
}
